package com.sweet.pack;

import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.*;
import com.sweet.lang.StringUtil;

/**
 * JS工具类
 *
 * @author limi
 * @date 2022/10/17 16:45
 */
public class JsUtil {
    /**
     * 压缩代码
     * 仅压缩，无法加密
     *
     * @param code
     * @return
     */
    public static String compress(String code) {
        if (StringUtil.isBlank(code)) {
            return "";
        }

        CompilerOptions options = new CompilerOptions();
        // Simple mode is used here, but additional options could be set, too.
        CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

        // To get the complete set of externs, the logic in
        // CompilerRunner.getDefaultExterns() should be used here.
        SourceFile extern = SourceFile.fromCode("externs.js",
                "function alert(x) {}");

        // The dummy input name "input.js" is used here so that any warnings or
        // errors will cite line numbers in terms of input.js.
        SourceFile input = SourceFile.fromCode("input.js", code);

        // compile() returns a Result, but it is not needed here.
        Compiler compiler = new Compiler();
        compiler.compile(extern, input, options);

        // The compiler is responsible for generating the compiled code; it is not
        // accessible via the Result.
        if (compiler.getErrorCount() > 0) {
            StringBuilder errorInfo = new StringBuilder();
            for (JSError jsError : compiler.getErrors()) {
                errorInfo.append(jsError.toString());
            }
            return "";
        }
        return compiler.toSource();
    }
}